package com.ys.web.user.app;

import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.service.WxOAuth2Service;
import me.chanjar.weixin.open.api.impl.WxOpenOAuth2ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP信息管理器 管理平台的app信息
 * 定时从数据库加载app信息到内存中
 */
@Service
@Slf4j
public class AppInfoManager implements Runnable{
	@Autowired
	private AppInfoService appInfoModel;
	
	private static Map<String, AppInfo> apps = new HashMap<>();
	
	/**
	 * 通过应用Key获取应用信息
	 * 应用Key就是数据库的app_id 和 app 的 id 不一样
	 * @param appKey 应用Key
	 * @return 应用信息
	 */
	public static AppInfo get(String appKey){
		if(StringHandler.isEmpty(appKey))return new ArrayList<>(apps.values()).get(0);
		return apps.get(appKey);
	}
	
	@PostConstruct
	public void init(){
		load();
		new Thread(this).start();
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(60000);
				load();
			} catch (Exception e) {}
		}
	}

	public WxOAuth2Service wxMaService(AppInfo appInfo) {
		WxOAuth2Service wxOAuth2Service = new WxOpenOAuth2ServiceImpl(appInfo.getAppId(),appInfo.getSecret());
		return wxOAuth2Service;
	}

	private void load(){
		try {
			List<AppInfo> list = appInfoModel.list();
			if(StringHandler.isEmpty(list)){
				return;
			}
			for(AppInfo app : list){
				app.setWxOAuth2Service(wxMaService(app));
				apps.put(app.getAppId(), app);
			}
			log.info("加载app列表------------------完成");
		} catch (Exception e) {
			Logger.error("加载app列表", e);
		}
	}
	
}
